﻿using CinemaMaestro.DataLayer.Contracts;
using CinemaMaestro.DataLayer.Contracts.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace CinemaMaestro.DataLayer.Entity
{
    public class ScreeningRepository : IRepository<Screening>
    {
        private DbSet<Screening> _dbSet;
        private DbContext _ctx;

        public ScreeningRepository(DbContext context)
        {
            _dbSet = context.Set<Screening>();
            _ctx = context;
        }

        public IQueryable<Screening> Read()
        {
            return _dbSet;
        }

        public Screening Create(Screening entity)
        {
            _ctx.Set<Movie>().Attach(entity.Movie);
            _ctx.Set<Language>().Attach(entity.Language);
            _ctx.Set<Room>().Attach(entity.Room);
            return _dbSet.Add(entity);
        }

        public void Update(Screening entity)
        {
            var existingScreening = _dbSet.First(x => x.Id == entity.Id);
            _ctx.Set<Movie>().Attach(entity.Movie);
            _ctx.Set<Language>().Attach(entity.Language);
            _ctx.Set<Room>().Attach(entity.Room);
            existingScreening.Language = entity.Language;
            existingScreening.Movie = entity.Movie;
            existingScreening.Room = entity.Room;
            existingScreening.StartDate = entity.StartDate;
            existingScreening.EndDate = entity.EndDate;
            existingScreening.Price = entity.Price;
            existingScreening.DiscountedPrice = entity.DiscountedPrice;
        }

        public bool Delete(int id)
        {
            var instance = _dbSet.
                FirstOrDefault(x => x.Id == id);

            if (instance != null)
            {
                _dbSet.Remove(instance);
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}
